package com.atguigu.flink.chapter11;

import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

import java.time.ZoneOffset;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/8/20 10:54
 */
public class Flink20_SQL_Group_Window {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        
        env.setParallelism(1);
    
        
        StreamTableEnvironment tenv = StreamTableEnvironment.create(env);
        tenv.getConfig().setLocalTimeZone(ZoneOffset.ofHours(0)); // 设置事件时间使用的时区
        // 1. 需要有一个时间戳类型的字段(作为事件属性)  2. 需要定义水印
        // bigint->timestamp   | bigint ->(from_unixtime) "datatime 的字符" ->(to_timestamp) timestamp
        tenv.executeSql("create table sensor(" +
                            "   id string, " +
                            "   ts bigint, " +
                            "   vc int, " +
                            "   et as to_timestamp(from_unixtime(ts/1000)), " +
                            "   watermark for et as et - interval '3' second " +
                            ")with(" +
                            "   'connector' = 'filesystem', " +
                            "   'path' = 'input/sensor.txt'," +
                            "   'format' = 'csv' " +
                            ")");
        
        
       /* tenv.sqlQuery("select " +
                          " id, " +
                          " tumble_start(et, interval '5' second) stt, " +
                          " tumble_end(et, interval '5' second) edt, " +
                          " sum(vc) vc_sum " +
                          "from sensor " +
                          "group by id, tumble(et, interval '5' second)")
            .execute().print();*/
    
        /*tenv.sqlQuery("select " +
                          " id, " +
                          " hop_start(et, interval '2' second, interval '5' second) stt, " +
                          " hop_end(et, interval '2' second, interval '5' second) edt, " +
                          " sum(vc) vc_sum " +
                          "from sensor " +
                          "group by id, hop(et, interval '2' second, interval '5' second)")
            .execute().print();*/
    
        tenv.sqlQuery("select " +
                          " id, " +
                          " SESSION_start(et, interval '2' second) stt, " +
                          " SESSION_end(et, interval '2' second) edt, " +
                          " sum(vc) vc_sum " +
                          "from sensor " +
                          "group by id, SESSION(et, interval '2' second)")
            .execute().print();
      
       
        
    }
}
